package org.example.leetcode.core.config;

import org.example.leetcode.common.domain.SysUser;
import org.example.leetcode.common.utils.UserInfo;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author topto
 */
@Component
public class TaskConfig implements AsyncConfigurer {
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor taskExecutor=new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(10);
        taskExecutor.setMaxPoolSize(100);
        taskExecutor.setQueueCapacity(10);
        taskExecutor.setThreadNamePrefix("AsyncThread");

        taskExecutor.setTaskDecorator(task->{
            SysUser userInfo = UserInfo.getUserInfo();
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            return ()->{
                UserInfo.setUserInfo(userInfo);
                RequestContextHolder.setRequestAttributes(servletRequestAttributes,true);
                task.run();
            };
        });
        return taskExecutor;
    }
}
